package org.droid.campusorder;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.util.Hashtable;
import org.droid.R;
import org.droid.campusorder.action.RespGetCanteenAction;
import org.droid.campusorder.bean.RespCanteenBean;
import org.droid.campusorder.common.Config;
import org.droid.campusorder.common.GlobalData;
import org.droid.campusorder.manager.NetManager;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.sqlite.SQLiteDatabase;
import android.net.ConnectivityManager;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;

public class LoadingActivity extends MyActivity {
	private RespGetCanteenAction respGetCanteenAction;
	private RespCanteenBean rcb;
	private Hashtable<String, String> ht;
	ConnectivityManager mConnectivity;// 网络连接

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.loading);
		try {
			File file = new File(GlobalData.dirPath);
			if (!file.exists()) {
				file.mkdirs();
			}
			String dbFilename = "campus_order.db";
			GlobalData.localDatabase = openDatabase(dbFilename);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	private void closeLoad() {
		this.finish();
	}

	@Override
	protected void onResume() {
		// TODO Auto-generated method stub
		super.onResume();
		// 判断网络是否可用
		if (NetManager.isNetworkAvailable(this)) {
			handler.postDelayed(handlerThread, 500);
		} else {
			setNetDialog();
		}
	}

	/**
	 * 用Handler来更新UI
	 */
	private Handler handler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			switch (msg.what) {
			case 0:
				System.out.println("出错~~");
				new AlertDialog.Builder(LoadingActivity.this)
						.setTitle("出错啦~")
						.setMessage("数据请求失败！")
						.setPositiveButton("重试",
								new DialogInterface.OnClickListener() {

									@Override
									public void onClick(DialogInterface arg0,
											int arg1) {
										// TODO Auto-generated method stub
										handler.post(handlerThread);
									}
								})
						.setNegativeButton("退出",
								new DialogInterface.OnClickListener() {

									@Override
									public void onClick(DialogInterface arg0,
											int arg1) {
										// TODO Auto-generated method stub
										System.exit(0);
									}
								}).show();
				break;

			}
		}
	};

	// 设置网络对话框
	public void setNetDialog() {
		AlertDialog.Builder builder = new AlertDialog.Builder(
				LoadingActivity.this);
		builder.setTitle("提示");
		builder.setMessage("未检测到网络信号，请检查您的网络。");
		builder.setPositiveButton("设置网络",
				new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int which) {
						// TODO Auto-generated method stub
						startActivity(new Intent(
								android.provider.Settings.ACTION_WIRELESS_SETTINGS));
					}
				});
		builder.setNegativeButton("退出", new DialogInterface.OnClickListener() {
			public void onClick(DialogInterface dialog, int which) {
				// TODO Auto-generated method stub
				LoadingActivity.this.finish();
			}
		});
		builder.setCancelable(false);
		builder.show();
	}

	private Runnable handlerThread = new Runnable() {
		public void run() {
			try {
				respGetCanteenAction = new RespGetCanteenAction(
						LoadingActivity.this);
				ht = new Hashtable<String, String>();
				ht.put("forword", "GetCanteen");
				rcb = (RespCanteenBean) respGetCanteenAction.getMsgFromNetwork(
						null, Config.SubConfig.Req, ht);
				System.out.println("食堂返回码：" + rcb.getReturnCode());
				// 将返回的食堂Bean放入公共信息GlobalData
				GlobalData.canteenBeanList = rcb.getCanteenBeanList();
				Intent intent = new Intent();
				intent.setClass(LoadingActivity.this, MainActivity.class);
				startActivity(intent);
				closeLoad();
			} catch (Exception e) {
				handler.sendEmptyMessage(0);
				// e.printStackTrace();
			}
		}
	};

	/** 复制和打开SD卡上的数据库文件*/
	private SQLiteDatabase openDatabase(String database_filename) {
		String database_path = GlobalData.dirPath;
		try {
			// 获得dictionary.db文件的绝对路径
			String databaseFilename = database_path + "/" + database_filename;
			File dir = new File(database_path);
			// 如果/sdcard/campus_order目录中存在，创建这个目录
			if (!dir.exists()) {
				dir.mkdir();
			}
			// 如果在/sdcard/campus_order目录中不存在
			// campus_order.db文件，则从res\raw目录中复制这个文件到
			// SD卡的目录（/sdcard/campus_order）
			if (!(new File(databaseFilename)).exists()) {
				// 获得封装dictionary.db文件的InputStream对象
				InputStream is = getResources().openRawResource(
						R.raw.campus_order);
				int fileSize = is.available(); // 文件大小
				System.out.println(fileSize);
				FileOutputStream fos = new FileOutputStream(databaseFilename);
				byte[] buffer = new byte[fileSize];
				int count = 0;
				// 开始复制dictionary.db文件
				while ((count = is.read(buffer)) > 0) {
					fos.write(buffer, 0, count);
				}
				fos.close();
				is.close();
			}
			// 打开/sdcard/campus_order目录中的campus_order.db文件
			SQLiteDatabase database = SQLiteDatabase.openOrCreateDatabase(
					databaseFilename, null);
			return database;
		} catch (Exception e) {
			System.out.println(e.getMessage());
		}
		return null;
	}

}
